//
//  AATRaderView.swift
//  StringForSwift
//
//  Created by DeLong Yang on 2017/7/25.
//  Copyright © 2017年 YiXue. All rights reserved.
/*
    这个view 主要用来展示 雷达旋转的动画
    会如果有增加了 一个新的蓝牙设备 那么 会增加一个 随机地点 的闪烁星星的显示
 
 */

import UIKit

class AATRaderView: UIView {

    //  we need to draw circle in this view  private var
    private var allStarPoints:NSMutableArray = NSMutableArray();
    
    private let kStartLen:CGFloat = 10.0;  // star length
    
    
    override func draw(_ rect: CGRect) {
        // Drawing code
        let  context = UIGraphicsGetCurrentContext()  // 获取当前的画布
        
        // move to the cente
        UIGraphicsGetCurrentContext()?.translateBy(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0)
        let  width:CGFloat = self.frame.size.width
        let  height:CGFloat = self.frame.size.height
        var  length:CGFloat = 0.0
        if width>=height {
            length =  height
        }else{
            length = width
        }
        
        //
//        context?.translateBy(x: width/2, y: height/2)
        context?.setStrokeColor(UIColor.blue.cgColor)
        context?.setLineWidth(1)
        
        let radiusIncre:CGFloat = length*0.15
        
        for i in 0..<4{
            let x = (CGFloat(i)*radiusIncre)
            context?.move(to: CGPoint(x: x, y: 0.0))
            context?.addArc(center: CGPoint(x:0,y:0), radius: x, startAngle: 0, endAngle: CGFloat(Double.pi*2), clockwise: false)
        }
        
        context?.strokePath()
        

    }

    var indicatorView:AATRaderIndicatorView = AATRaderIndicatorView()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //
        indicatorView = AATRaderIndicatorView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
        indicatorView.backgroundColor = UIColor.clear
        self.addSubview(indicatorView)
        
        //
        initStartPoints()
    }
    
    
    
    //
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // TODO: private  method 
    fileprivate func initStartPoints(){
        //
        let  width:CGFloat = self.frame.size.width
        let height:CGFloat = self.frame.size.height
        var length:CGFloat = 0.0;
        
        // 为了避免 超出范围的情况 我们的用其中最小的边 作为 星星的坐标点
        if width>=height {
            length = height
        }else{
            length = width
        }
        
        //
        let number:Int = Int(length/kStartLen);
        
        // 从 0 开始 的双循环  ..<     使用这个 区分 ... 的封闭区间
        for i in 0..<number {
            for j in 0..<number{
                let point:CGPoint = CGPoint(x: i, y: j)
                allStarPoints.add(point)  // 将这个点 加进来
            }
        }
        
        
        
        
    }
    
    
    // TODO:  public method   start/stop scan animation  showAnimationStar
    func startScan() {
        
        // 注意 总共有 三个方向 的旋转
        let scanningAnimation = CABasicAnimation.init(keyPath: "transform")
        var transform = CATransform3DMakeRotation(CGFloat(0.5 * Double.pi), 0, 0, 1);
        transform.m34 = 0.05
        
        scanningAnimation.toValue = transform;
        scanningAnimation.autoreverses = false;
        scanningAnimation.duration = 2.0
        scanningAnimation.repeatCount = HUGE
        scanningAnimation.fillMode = kCAFillModeBackwards
        scanningAnimation.isCumulative = true
        scanningAnimation.isRemovedOnCompletion = false
        indicatorView.layer.add(scanningAnimation, forKey: "scanningAnimation")
        
        
        
    }
    
    // stop scan animation
    func stopScan() {
        indicatorView.layer.removeAnimation(forKey: "scanningAnimation")
    }
    
    //  if add a new star show in the view
    func showOneMoreStarView(){
        
        //
        let totalCount:UInt32 = UInt32(allStarPoints.count)
        let random = arc4random()%totalCount  // 产生的随机数
        
        print(random)
        let point:CGPoint = allStarPoints[Int(random)] as! CGPoint;
        
        //
        let  width:CGFloat = self.frame.size.width
        let  height:CGFloat = self.frame.size.height
        var  length:CGFloat = 0.0
        if width>=height {
            length =  height
        }else{
            length = width
        }

        let  frame = CGRect(x: point.x*10 + (width - height)*0.5 , y: (point.y+2)*kStartLen, width: kStartLen, height: kStartLen);
        let  starView = UIView(frame: frame)
        starView.backgroundColor = UIColor.yellow
        starView.layer.cornerRadius = kStartLen * 0.5
        self.addSubview(starView)
        
        starView.startPulseWith(color: UIColor.red, scaleFrom: 0.2, toScale: 2.0, frequency: 2.0, opacity: 1, animationType: .RadarPulsing)
        
        allStarPoints.removeObject(at: Int(random))
        
    }
}


//  plusing Animation  for uiview  we add plusing animation
extension  UIView{
   
    static let YGPlusKey = "YGPlusKey"
    static let YGRadarKey = "YGRadarKey"
    static let YGLayerName = "YGLayerName"
    
    enum YGPulseViewAnimationType {
        case RegularPulsing,RadarPulsing
    }

    //  default params plusing animation
    func startPlusWithColor(color:UIColor){
        startPulseWith(color: color, scaleFrom: 1.2, toScale: 1.4, frequency: 1.0, opacity: 0.7, animationType: .RegularPulsing)
    }
    
    //
    func startPulseWith(color:UIColor,animationType:YGPulseViewAnimationType) {
        let frequency = animationType == .RadarPulsing ? 1.5 : 1.0
        let startScale = animationType == .RegularPulsing ? 1.0 : 1.2
        
        startPulseWith(color: color, scaleFrom: CGFloat(startScale), toScale: 1.4, frequency: CGFloat(frequency), opacity: 0.7, animationType: animationType)
        
    }
    
    //
    func startPulseWith(color:UIColor, scaleFrom:CGFloat, toScale:CGFloat , frequency:CGFloat, opacity:CGFloat ,animationType:YGPulseViewAnimationType) {
        
        let externalBorder = CALayer()
        externalBorder.frame = self.frame;
        externalBorder.cornerRadius = self.layer.cornerRadius
        externalBorder.backgroundColor = color.cgColor
        externalBorder.opacity = Float(opacity)
        externalBorder.name = UIView.YGLayerName
        
        self.layer.masksToBounds = false
        self.layer.superlayer?.insertSublayer(externalBorder, below: self.layer)
        
        let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
        scaleAnimation.fromValue = scaleFrom
        scaleAnimation.toValue = toScale
        scaleAnimation.duration = CFTimeInterval(frequency)  // swift 中有严格的类型限制
        scaleAnimation.autoreverses = (animationType == .RegularPulsing)   // 需要重复的 动画
        scaleAnimation.repeatCount = HUGE
        externalBorder.add(scaleAnimation, forKey: UIView.YGPlusKey)
        
        //
        if animationType == .RadarPulsing {
            let opacityAnimation = CABasicAnimation(keyPath: "opacity")
            opacityAnimation.fromValue = opacity
            opacityAnimation.toValue = 0.0
            opacityAnimation.duration = CFTimeInterval(frequency)
            opacityAnimation.autoreverses = false
            opacityAnimation.repeatCount = HUGE
            externalBorder.add(opacityAnimation, forKey: UIView.YGRadarKey)
            
        }
        
        
    }
    
    //
    func stopPulse() {
        
        self.layer.removeAnimation(forKey: UIView.YGRadarKey)
        self.layer.removeAnimation(forKey: UIView.YGPlusKey)
    
        let layer = externalBorderLayer()
        
        if layer != nil {
            layer?.removeFromSuperlayer()
        }
        
    }
    
    
    func externalBorderLayer() -> CALayer? {
        
        for layer in  (self.layer.superlayer?.sublayers)!{
            if layer.name == UIView.YGLayerName {
                return layer
            }
        }
        
        return nil
    }
    
}

























